﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Agro.Library;
using SN.Core;
using Agro.Models;
using Ninject;
using Agro.Services;
using SN.Data;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Agro.Web.Areas.SystemManage.Controllers {
    public class RoleController : BaseController {
        [Inject]
        public IRoleService RoleService { get; set; }
        [Inject]
        public IUserService UserService { get; set; }

        [AuthorizeMenu]
        public ActionResult RoleList() {
            ViewBag.IsAdmin = CurrUser.UserInfo.IsAdmin()?"1":"0"; //非管理员，不能修改角色
            return View();
        }
        [HttpGet]
        public ActionResult RoleDetail(string id) {
            T_Role role = new T_Role();
            if (!string.IsNullOrEmpty(id)) {
                role = RoleService.GetEntity<T_Role>(T_Role._.Role_ID == id);
                ViewBag.type = "edit";
            }
            else {
                role.Role_IsAvailable = "1"; //是否有效
                role.Role_IsInnerRole = "0";//是否内置角色
                role.Role_CreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                ViewBag.type = "add";
            }
            return View(role);
        }

        [HttpGet]
        public ActionResult RoleUsers(string RoleId) {
            ViewBag.RoleId = RoleId;
            return View();
        }
        [HttpGet]
        public ActionResult RoleUserList(string RoleId) {
            ViewBag.RoleID = RoleId;
            return View();
        }

        public ActionResult GetUserList(string id, QueryBase query) {
            //QueryCreator qc = QueryCreator.NewCreator().From<T_User_Role>().AddWhere(T_User_Role._.UR_RoleID == id).AddField(T_User_Role._.UR_UserID);
            //WhereClip where = !T_User._.User_ID.In(qc) && T_Organization._.Organization_ID.In(orgarr);
            var dt = RoleService.GetUserNotInRole(query,id, CurrUser.UserInfo.User_OrganizationID);
            return JqGrid(dt, query);
        }
        public ActionResult GetRoleUsers(string id, QueryBase query) {
           // DataTable dataTable = BaseService.DB.FromSql(string.Format("Select Organization_ID From GetChildrenOrg({0})", CurrUser.UserInfo.User_OrganizationID)).ToDataTable();
           // WhereClip where = T_User_Role._.UR_RoleID == id && T_Organization._.Organization_ID.In(dataTable.);
            //WhereClip where = T_User_Role._.UR_RoleID == id;
            var dt = RoleService.GetRoleUsers(query,id, CurrUser.UserInfo.User_OrganizationID);
            return JqGrid(dt, query);
        }
        [HttpPost]
        public ActionResult RemoveRoleUser(string roleId, string userid) {
            string msg = string.Empty;
            msg = RoleService.RemoveRoleUser(roleId, userid);
            return Json(msg);
        }
        [HttpPost]
        public ActionResult GetRoleList(QueryBase query) {
            WhereClip where = WhereClip.All;
            var list = RoleService.GetEntityList<T_Role>(where, query);
            return JqGrid(list, query);
        }

        [HttpPost]
        public ActionResult SaveRole(int Role_ID, FormCollection collection) {
            T_Role Role = new T_Role();
            if (Role_ID > 0)
            {
                Role = RoleService.GetEntity<T_Role>(T_Role._.Role_ID == Role_ID);
            }
            else
            {
                Role.Role_CreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                Role.Role_CreateUserID = CurrUser.UserInfo.User_Name;
            }
            UpdateModel(Role, collection);
            string msg = string.Empty;
            RoleService.SaveRole(Role, out msg);
            return SNJson(Role.Role_ID, msg);
        }
        [HttpPost]
        public ActionResult Delete_Role(string ids) {
            string msg = string.Empty;
            RoleService.DeleteRoles(ids, out msg);
            return SNJson(msg);
        }


        #region 角色功能权限
        [HttpGet]
        public ActionResult RolePermissionList(string RoleId) {
            ViewBag.RoleID = RoleId;
            return View();
        }

        public ActionResult GetRoleMenuTreeNodes(int id) {
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("MenuID", typeof(int));
            dtResult.Columns.Add("FatherMenuID", typeof(int));
            dtResult.Columns.Add("Name", typeof(string));
            dtResult.Columns.Add("checked", typeof(bool));
            IList<T_Menu> menuList = RoleService.GetEntityList<T_Menu>(WhereClip.All && new Field("isnull(menu_isdel,'0')") == "0");
            menuList = menuList.OrderBy(m => m.Menu_Order).ToList();
            IList<T_Role_Permission> roleMenuList = RoleService.GetEntityList<T_Role_Permission>(T_Role_Permission._.RP_RoleID == id && T_Role_Permission._.RP_Type == "T_Menu");
            DataRow dr = null;
            foreach (var item in menuList) {
                dr = dtResult.NewRow();
                dr["MenuID"] = item.Menu_ID;
                dr["FatherMenuID"] = item.Menu_ParentID;
                dr["Name"] = item.Menu_NAME;
                dr["checked"] = roleMenuList.Count(m => m.RP_TableID == item.Menu_ID.ToString()) > 0;
                dtResult.Rows.Add(dr);
            }
            string result = JsonConvert.SerializeObject(dtResult, new DataTableConverter());
            return Content(result);
        }

        

        [HttpPost]
        public ActionResult SaveRoleMenus(int roleId, string menuIds) {
            string Msg = RoleService.SaveRoleMenus(roleId, menuIds);
            return SNJson(Msg);
        }
        #endregion


        [HttpPost]
        public ActionResult SaveRoleUsers(string roleId, string userIds) {
            string Msg = RoleService.SaveRoleUsers(roleId, userIds);
            return SNJson(Msg);
        }

        public ActionResult RoleAction(int id) {
            ViewBag.Menus = GetMenuOptionList();
            ViewBag.RoleID = id;
            return View();
        }

        public ActionResult GetRoleActionTreeNodes(int roleId, int menuId) {
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("ActionID", typeof(int));
            dtResult.Columns.Add("ActionName", typeof(string));
            dtResult.Columns.Add("checked", typeof(bool));
            IList<T_Action> actionList = RoleService.GetEntityList<T_Action>(T_Action._.MenuID == menuId);
            IList<T_RoleAction> roleActionList = RoleService.GetEntityList<T_RoleAction>(T_RoleAction._.RoleID == roleId);
            DataRow dr = null;
            foreach (var action in actionList) {
                dr = dtResult.NewRow();
                dr["ActionID"] = action.ActionID;
                dr["ActionName"] = string.Format("{0}({1})", action.ActionName, action.ActionCode);
                dr["checked"] = roleActionList.Count(m => m.ActionID == action.ActionID) > 0;
                dtResult.Rows.Add(dr);
            }
            string result = JsonConvert.SerializeObject(dtResult, new DataTableConverter());
            return Content(result);
        }

        [HttpPost]
        public ActionResult SaveRoleActions(int roleId, int menuId, string actionIds) {
            RoleService.SaveRoleActions(roleId, menuId, actionIds);
            return SNJson(string.Empty);
        }


        IList<SelectListItem> GetMenuOptionList() {
            IList<T_Menu> topMenu = RoleService.GetEntityList<T_Menu>(T_Menu._.Menu_ParentID == 0 && new Field("isnull(menu_isdel,'0')") == "0").OrderBy(m => m.Menu_Order).ToList();

            List<SelectListItem> optionList = new List<SelectListItem>();
            foreach (var item in topMenu) {
                optionList.Add(new SelectListItem { Text = item.Menu_NAME, Value = item.Menu_ID.ToString() });
                recurMenuList(optionList, item.Menu_ID, "|----");
            }
            return optionList;
        }

        void recurMenuList(IList<SelectListItem> optionList, int fatherId, string prefix) {
            var list = RoleService.GetEntityList<T_Menu>(T_Menu._.Menu_ParentID == fatherId && new Field("isnull(menu_isdel,'0')") == "0").OrderBy(m => m.Menu_Order).ToList();
            foreach (var item in list) {
                optionList.Add(new SelectListItem { Text = prefix + item.Menu_NAME, Value = item.Menu_ID.ToString() });
                recurMenuList(optionList, item.Menu_ID, prefix + "----");
            }
        }
    }
}
